<?php
// +----------------------------------------------------------------------
// | OneKeyAdmin [ Believe that you can do better ]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://onekeyadmin.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: MUKE <513038996@qq.com>
// +----------------------------------------------------------------------
namespace app\admin\controller;

use think\facade\View;
use think\facade\Filesystem;
use think\exception\ValidateException;
use app\admin\addons\Image;
use app\admin\BaseController;
use app\addons\File as FileAddons;
use app\admin\model\File as FileModel;
use app\admin\validate\File as FileValidate;
/**
 * 文件
 */
class File extends BaseController
{
    /**
     * 显示资源列表
     */
    public function index()
    {
        if ($this->request->isPost()) {
            $input = input();
            $pageSize  = $input['type'] === 'recycle' ? 200 : 30;
            $order     = $input['order'] === 'ascending' ? 'asc' : 'desc';
            $count     = FileModel::withSearch(['keyword','type','pid','status'], $input)->count();
            $data      = FileModel::withSearch(['keyword','type','pid','status'], $input)
            ->order('folder','desc')
            ->order($input['prop'], $order)
            ->page($input['page'], $pageSize)
            ->select();
             $totalPage = ceil($count / $pageSize);
            return json(['status' => 'success', 'message' => '', 'data' => $data, 'count' => $count, 'totalPage' => $totalPage]);
        } else {
            return View::fetch();
        }
    }

    /**
     * 粘贴
     */
    public function paste()
    {
        try {
            $input = input();
            validate(FileValidate::class)->scene('paste')->check($input);
            $data = $input['data'];
            $pid  = $input['pid'];
            $save = [];
            $date = date('Y-m-d H:i:s');
            foreach ($data as $key => $val) {
                // 剪切不需要换ID
                $item['id']          = (int)$val['id'];
                $item['pid']         = (int)$pid;
                $item['title']       = $val['title'];
                $item['url']         = $val['url'];
                $item['size']        = (int)$val['size'];
                $item['type']        = $val['type'];
                $item['folder']      = (int)$val['folder'];
                $item['create_time'] = $date;
                $item['status']      = 1;
                array_push($save, $item);
            }
            $model = new FileModel;
            $data  = $model->saveAll($save);
            return json(['status' => 'success', 'message' => '粘贴成功', 'data' => $data]);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 保存更新的资源
     */
    public function update()
    {
        try {
            $input = input();
            validate(FileValidate::class)->scene('field')->check($input);
            $save  = FileModel::find($input['id']);
            $field = $input['field'];
            $save->$field = $input['value'];
            $save->save();
            return json(['status' => 'success', 'message' => '修改成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        $input      = input();
        $file       = $this->request->file('file');
        $limitExt   = config('upload.ext');
        $limitSize  = config('upload.size');
        $name       = $_FILES['file']['name'];
        $size       = $_FILES['file']['size'];
        $type       = FileAddons::getType($limitExt, $name);
        if (! empty($type)) {
            try {
                $limitExt  = $limitExt[$type];
                $limitSize = $limitSize[$type];
                validate([ 'file' => ['fileSize' => $limitSize, 'fileExt' => $limitExt] ])->check(['file' => $file]);
                $url  = Filesystem::putFile($type, $file);
                $url  = '/upload/' . str_replace('\\', '/', $url);
                $save = FileModel::create([
                    'pid'         => $input['pid'],
                    'title'       => $name,
                    'url'         => $url,
                    'size'        => $size,
                    'type'        => $type,
                    'folder'      => 0,
                    'create_time' => date('Y-m-d H:i:s'),
                    'status'      => 1,
                ]);
                if ($type === "image") {
                    // 封面图片
                    Image::thumb($save['url']);
                    // 上传钩子
                    event("UploadEnd", $save['url']);
                }
                return json(['status' => 'success', 'message' => '上传成功', 'data' => $save]);
            } catch (ValidateException $e) {
                return json(['status' => 'error', 'message' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 'error', 'message' => '此类型的文件不支持上传！']);
        }
    }

    /**
     * 上传指定目录文件
     */
    public function uploadAppoint()
    {
        $input = input();
        if (isset($input['name'])) {
            try {
                $file = $this->request->file('file');
                $path = 'upload';
                $size = isset($input['size']) ? $input['size'] : 1*1024*1024;
                $ext  = isset($input['ext']) ? $input['ext'] : '';
                $name = $input['name'].'.'.$ext;
                validate([ 'file' => ['fileSize' => $size, 'fileExt' => $ext] ])->check(['file' => $file]);
                Filesystem::putFileAs('/', $file, $name);
                return json(['status' => 'success', 'message' => '上传成功', 'url' => '/'.$path.'/'.$name]);
            } catch (ValidateException $e) {
                return json(['status' => 'error', 'message' => $e->getMessage()]);
            }
        } else {
            return json(['status' => 'error', 'message' => '请指定文件名称！']);
        }
    }

    // 计算文件夹大小
    public function countSizeFolder() 
    {
        try{
            $input = input();
            validate(FileValidate::class)->scene('countFolder')->check($input);
            $data = FileModel::countSizeFolder($input['id']);
            return json(['status' => 'success', 'message' => '新增成功', 'data' => $data]);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 新建文件夹
     */
    public function addFolder() 
    {
        try{
            $input = input();
            validate(FileValidate::class)->scene('addFolder')->check($input);
            $save = FileModel::create([
                'pid'         => $input['pid'],
                'title'       => '新建文件夹',
                'url'         => '',
                'size'        => 0,
                'type'        => $input['type'],
                'folder'      => 1,
                'create_time' => date('Y-m-d H:i:s'),
                'status'      => 1,
            ]);
            return json(['status' => 'success', 'message' => '新增成功', 'data' => $save]);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 回收站文件(删除/还原)
     */
    public function recycle()
    {
        try {
            $input = input();
            validate(FileValidate::class)->scene('delOrRecycle')->check($input);
            FileModel::whereIn('id', $input['ids'])->update(['status' =>  $input['status']]);
            return json(['status' => 'success', 'message' => '已放入回收站']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }

    /**
     * 永久删除文件
     */
    public function delete()
    {
        try {
            $input = input();
            if (isset($input['ids'])) {
                validate(FileValidate::class)->scene('delOrRecycle')->check($input);
                FileModel::recursiveDestroy($input['ids']);
            } else {
                $all = FileModel::where('status', 0)->column('url');
                foreach ($all as $key => $name) {
                    $file  = app()->getRootPath() . 'public' . $name;
                    $arr   = explode('.', $file);
                    if (count($arr) > 1) {
                        $cover = $arr[0] . '40x40.' . $arr[1];
                        if(is_file($file)) unlink($file);
                        if(is_file($cover)) unlink($cover);
                    }
                }
                FileModel::where('status', 0)->delete();
            }
            return json(['status' => 'success', 'message' => '删除成功']);
        } catch ( ValidateException $e ) {
            return json($e->getError());
        }
    }
}
